-- UIDungeonRevive
-- Created by chengb Jan/23/2015
-- 地牢复活界面

-- UIDungeonRevive继承自Layer
UIDungeonRevive = class("UIDungeonRevive", function()
    return cc.Layer:create();
end);

function UIDungeonRevive.create()
    return UIDungeonRevive.new();
end

-- 构造函数
function UIDungeonRevive:ctor()
    self:setName("UIDungeonRevive");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/dungeon/DungeonRevive.csb");
    self:addChild(node);
    self.node = node;

    -- 当前是否有窗体动画在播放
    self.isPlaying = false;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 10);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIDungeonRevive:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- 特效节点居中并缩放至合适大小
    AlignM.alignToCenter(node, "effect_node");
end

-- 注册事件处理回调函数
function UIDungeonRevive:registerEventCallback()
    -- 注册复活的回调
    EventMgr.register("UIDungeonRevive", event.HERO_REVIVE, function()
        self:whenRevive();
    end);

    -- 注册玩家字段变化的回调
    ME.user.dbase:registerCb("UIDungeonRevive", { "gem", }, function()
        self:redraw();
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIDungeonRevive", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIDungeonRevive" then
            local function showTopMenu()
                -- 显示钻石栏
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
                UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);
            end
            performWithDelay(self, showTopMenu, 3.0);
        end

        if "UIBossEffect" == para["get"] then
            self:hideDialog();
        elseif "UIBossEffect" == para["lose"] then
            self:showDialog();
        end
    end);

    local topMenu = UIMgr.getCurrentScene().topMenu;

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            -- 反注册所有事件
            cclog("UIDungeonRevive界面析构清理");
            ME.user.dbase:removeCb("UIDungeonRevive", { "gem", });
            EventMgr.removeAll("UIDungeonRevive");

            self:stopAllActions();
            UIMgr.getCurrentScene().topMenu:setVisible(self.oldVisible);
            UIMgr:getCurrentScene().topMenu:setLocalZOrder(self.oldZOrder);
        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
                UIDungeonMgr:getCurLevel():hideTop();
            end

            -- 临时调高TOP_MENU的ZOrder
            self.oldVisible = topMenu:isVisible();
            UIMgr.getCurrentScene().topMenu:setVisible(true);
            self.oldZOrder = topMenu:getLocalZOrder();
        end
    end);
end

-- 隐藏界面
function UIDungeonRevive:hideDialog()
    local effectNode = findChildByName(self.node, "effect_node");
    effectNode:removeAllChildren();
    self.CT:stopAllActions();

    self.isHide = true;

    self.CT:setVisible(false);

    local bg = findChildByName(self.node, "bg");
    local fadeOut = cc.FadeOut:create(0.5);

    bg:stopAllActions();
    bg:runAction(cc.Sequence:create(fadeOut));
end

-- 显示界面
function UIDungeonRevive:showDialog()

    self.isHide = nil;

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();
end

-- 初始化窗口
function UIDungeonRevive:initForm()
    -- 先将主窗口隐藏
    local CT = findChildByName(self.node, "CT");
    self.CT = CT;
    CT:setVisible(false);

    -- 播放屏幕变暗的效果
    local bg = findChildByName(self.node, "bg");
    bg:setOpacity(0);
    local fadeIn = cc.FadeTo:create(1.5, 255);

    local callFunc = cc.CallFunc:create(function()
        -- 如果窗口还在播动画，那么return
        if self.isPlaying then
            return;
        end
        -- 播放收魂者冈布奥出现动画
        self:playSlimeAppear();
    end);

    bg:runAction(cc.Sequence:create(fadeIn, callFunc));
end

-- 播放收魂者冈布奥出现动画
function UIDungeonRevive:playSlimeAppear()
    if self.isHide then
        return;
    end

    -- 创建动画
    -- 音效
    AudioM.playFx("resurection");
    local effectAnim = createEffectAnim(1232);

    self.effectAnim = effectAnim;
    self.initOk = false;

    local function callback()
        -- 标记正在播动画
        self.isPlaying = true;

        -- 窗口从中心位置出现
        local initScale = self.CT:getScale();
        self.CT:setVisible(true);
        self.CT:setScale(0.3*initScale);

        -- 先放大再缩小
        self.CT:stopAllActions();
        local referTime = 0.15;
        local upTime    = 1.5*referTime;
        local downTime  = 2*referTime;
        local scaleUp   = cc.ScaleTo:create(upTime, 1.1*initScale);
        local scaleDown = cc.ScaleTo:create(downTime, 0.95*initScale);

        self.CT:runAction(cc.Sequence:create(scaleUp, scaleDown));

        local function callback2()
            -- 标记窗口初始化完毕
            self.initOk = true;

            -- 标记动画播放完成
            self.isPlaying = false;
        end
        performWithDelay(self, callback2, 0.5);

        local function loopPlay()
            -- 循环播放
            effectAnim:play(52, 122, true, 0.5);
        end

        -- 播放第二段动画
        effectAnim:play(32, 122, false, 0.5, loopPlay);
    end

    -- 播放第一段动画
    effectAnim:play(0, 31, false, 0.5, callback);

    -- TODO 播放音效

    local effectNode = findChildByName(self.node, "effect_node");
    effectNode:addChild(effectAnim);
end

-- 重绘
function UIDungeonRevive:redraw()
    -- 显示复活消耗
    local cost = DungeonLegacyM.calcReviveCost();
    local gemIconPath = getSmallAttribIconPath(FieldsM.query(cost[2], "icon"));
    local gemImg1 = findChildByName(self.node, "CT/cost_node/gem_icon");
    gemImg1:loadTexture(gemIconPath);

    local costAmountLabel = findChildByName(self.node, "CT/cost_node/cost_amount");
    TextStyleM.setOutlineStyle(costAmountLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    TextStyleM.setTextStyle(costAmountLabel, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_BROWN_YELLOW);
    costAmountLabel:setString(cost[3]);
    local reviveTip;

    if AwakeM.isInAwake() then
        -- 觉醒地牢中不能复活
        costAmountLabel:setString(getLocStr("default_value_text"));
        reviveTip = getLocStr("sky_instance_die_tip");
    elseif SkyInstanceM.isInSkyInstance() or not UnrealDungeonM.canRevive() then
        -- 如果在勇者斗恶龙副本中，并且保存过进度，则直接回档
        if BraveVSDragonM.isInBraveVSDragon() and BraveVSDragonM.hasSavedProgress() then
            costAmountLabel:setString(getLocStr("default_value_text"));
            reviveTip = getLocStr("brave_dragon_revive_tip");
        else
            -- 其他情况，天空副本中不能复活
            costAmountLabel:setString(getLocStr("default_value_text"));
            reviveTip = getLocStr("sky_instance_die_tip");
        end
    else
        costAmountLabel:setString(cost[3]);
        reviveTip = getLocStr("revive_tip_content");
    end

    -- 显示复活提示
    local contentLabel = findChildByName(self.node,"CT/tip_content");
    TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(contentLabel, reviveTip);
end

-- 重绘按钮
function UIDungeonRevive:redrawButton()
    -- 取消按钮
    local btnCancel = findChildByName(self.node, "CT/btn_revive");
    btnCancel:loadTextures("images/ui/button/btn_long_blue1.png", "images/ui/button/btn_long_blue2.png");
    btnCancel:setTitleText(getLocStr("btn_text_cancel"));
    local function onReviveCancel(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            self:redraw();
            self:registerTouchEvent();
        end
    end
    btnCancel:addTouchEventListener(onReviveCancel);

    -- 复活按钮
    local btnConfirm = findChildByName(self.node, "CT/btn_leave");
    btnConfirm:setTitleText(getLocStr("btn_text_ok"));
    btnConfirm:loadTextures("images/ui/button/btn_long_yellow1.png", "images/ui/button/btn_long_yellow2.png");
    local function onReviveComfirm(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            self:tryRevive();
        end
    end
    btnConfirm:addTouchEventListener(onReviveComfirm);

    -- 重绘文本
    local cost = DungeonLegacyM.calcReviveCost();
    local reviveTimes = ME.user:getReviveTimes();
    local contentLabel = findChildByName(self.node,"CT/tip_content");
    TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(contentLabel, string.format(getLocStr("revive_confirm"), cost[3], reviveTimes));
end

-- 离开时重绘界面
function UIDungeonRevive:redrawLeave()
    -- 确认按钮
    local btnLeaveConfirm = findChildByName(self.node, "CT/btn_revive");
    btnLeaveConfirm:setTitleText(getLocStr("btn_text_end_dungeon"));
    btnLeaveConfirm:loadTextures("images/ui/button/btn_long_yellow1.png", "images/ui/button/btn_long_yellow2.png");
    local function onLeaveConfirm(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            self:refuseRevive();
        end
    end
    btnLeaveConfirm:addTouchEventListener(onLeaveConfirm);

    -- 取消按钮
    local btnLeaveCancel = findChildByName(self.node,"CT/btn_leave");
    btnLeaveCancel:setTitleText(getLocStr("btn_text_think_again"));
    btnLeaveCancel:loadTextures("images/ui/button/btn_long_blue1.png", "images/ui/button/btn_long_blue2.png");
    local function onLeaveCancel(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            self:redraw();
            self:registerTouchEvent();
        end
    end
    btnLeaveCancel:addTouchEventListener(onLeaveCancel);

    -- 重绘提示文本
    local contentLabel = findChildByName(self.node,"CT/tip_content");
    TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(contentLabel, getLocStr("refuse_revive_tip"));
end

-- 注册点击事件
function UIDungeonRevive:registerTouchEvent()
    -- 注册复活按钮点击事件
    local btnRevive = findChildByName(self.node, "CT/btn_revive");
    btnRevive:loadTextures("images/ui/button/btn_long_yellow1.png", "images/ui/button/btn_long_yellow2.png");
    local function onReviveClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.initOk then
                -- 窗口尚未初始化完毕，不处理
                return;
            end

            AudioM.playFx("button_click");

            -- 如果在勇者斗恶龙副本中，并且保存过进度
            if BraveVSDragonM.isInBraveVSDragon() and BraveVSDragonM.hasSavedProgress() then
                -- 直接回到存档点
                BraveVSDragonM.readProgress();
                return;
            end

            -- 点击复活时重绘
            self:redrawButton();
        end
    end
    btnRevive:addTouchEventListener(onReviveClick);
    TextStyleM.setTextStyle(btnRevive, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnRevive:setTitleText(getLocStr("revive"));

    if AwakeM.isInAwake() then
        -- 觉醒地牢中不能复活
        setButtonEnabled(btnRevive, false);
    elseif SkyInstanceM.isInSkyInstance() or not UnrealDungeonM.canRevive() then
        -- 如果在勇者斗恶龙副本中，并且保存过进度
        if BraveVSDragonM.isInBraveVSDragon() and BraveVSDragonM.hasSavedProgress() then
            setButtonEnabled(btnRevive, true);
            btnRevive:setTitleText(getLocStr("btn_text_load"));
        else
            -- 其他情况，天空副本中不能复活
            setButtonEnabled(btnRevive, false);
        end
    else
        setButtonEnabled(btnRevive, true);
    end

    -- 注册离开按钮点击事件
    local btnLeave = findChildByName(self.node, "CT/btn_leave");
    btnLeave:loadTextures("images/ui/button/btn_long_blue1.png","images/ui/button/btn_long_blue2.png");
    local function onLeaveClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.initOk then
                -- 窗口尚未初始化完毕，不处理
                return;
            end

           AudioM.playFx("button_click");

           if AwakeM.isInAwake() then
                -- 如果在觉醒地牢中，直接离开
               self:refuseRevive();
               return;
           elseif SkyInstanceM.isInSkyInstance() or not UnrealDungeonM.canRevive() then
               -- 如果在天空特殊副本中，直接离开
               self:refuseRevive();
               return;
           end

           -- 重绘离开界面
           self:redrawLeave();
        end
    end
    btnLeave:addTouchEventListener(onLeaveClick);
    TextStyleM.setTextStyle(btnLeave, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnLeave:setTitleText(getLocStr("leave"));
end

-- 拒绝复活
function UIDungeonRevive:refuseRevive(isConfirm)
    local function callback()
        -- 还原TopMenu的ZOrder
        local topMenu = UIMgr:getCurrentScene().topMenu;
        topMenu:setVisible(self.oldVisible);
        topMenu:setLocalZOrder(self.oldZOrder);

        -- 关闭当前界面
        self:close();

        -- 如果当前在地牢副本中，需要先退出副本
        if DungeonInstanceM.isInInstance() then
            DungeonActionM.go("leave_instance");
        end

        -- 离开地牢
        UIDungeonMgr.leaveDungeon();
    end

    isConfirm = isConfirm or false;
    if not isConfirm then
        callback();
        return;
    end

    confirm(getLocStr("refuse_revive_tip"), callback);
end

-- 尝试复活
function UIDungeonRevive:tryRevive()
    -- 判断能否复活
    local ret = DungeonLegacyM.canRevive();
    if true ~= ret then
        if "gem_lack" == ret then
            -- 钻石不足
            showGemLackConfirm();
        else
            -- 未知原因
            cclog("复活失败，原因：" .. ret );
        end

        return;
    end

    -- 执行复活
    DungeonActionM.go("revive");
end

-- 关闭本界面
function UIDungeonRevive:close()
    if UIMgr.getCurrentScene():isOpen("UIDungeonRevive") then
        UIMgr.getCurrentScene():removeFormByName("UIDungeonRevive");
    end
end

-- 复活的回调
function UIDungeonRevive:whenRevive()
    -- 提示复活成功
    alert(getLocStr("revive_succ"));

    -- 还原地牢主界面的菜单
    if UIDungeonMgr:getCurLevel() then
        UIDungeonMgr:getCurLevel():showMenu();
        UIDungeonMgr:getCurLevel():showTop();
    end

    -- 还原TopMenu的ZOrder
    local topMenu = UIMgr:getCurrentScene().topMenu;
    topMenu:setVisible(self.oldVisible);
    topMenu:setLocalZOrder(self.oldZOrder);

    -- 若召唤了收魂者冈布奥，则在与其对话完毕后播放复活光效，这里直接关闭复活界面
    if DungeonLegacyM.canCallReviveSlime() then
        self:close();
        return;
    end

    -- 关闭当前复活窗口
    self.CT:setVisible(false);
    local effectNode = findChildByName(self.node, "effect_node");
    effectNode:setVisible(false);

    -- 背景淡出
    local outTime = 1;
    --local bg2 = findChildByName(self.node, "bg2");
    local fadeOut = cc.FadeOut:create(outTime);
    --bg2:runAction(fadeOut);

    local callFunc = cc.CallFunc:create(function()
        -- 关闭界面
        self:close();

        -- 播放复活光效
        playHeroReviveEffect();
    end);
    local bg = findChildByName(self.node, "bg");
    local fadeOut = cc.FadeOut:create(outTime);
    bg:runAction(cc.Sequence:create(fadeOut, callFunc));
end



